<template>
    <section class="container">
        <el-form inline>
            <el-form-item label="点位属性:">
                <el-checkbox-group v-model="pointValue" :min="1">
                    <el-checkbox :label="1">联网</el-checkbox>
                    <el-checkbox :label="2">非联网</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
        </el-form>
        <el-form inline>
            <el-form-item>
                <el-input v-model="keywords" placeholder="搜索楼盘名称">
                    <template #prefix>
                        <div class="label">
                            <el-icon :size="16">
                                <Search />
                            </el-icon>
                        </div>
                    </template>
                </el-input>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="getSelectedData">查询</el-button>
            </el-form-item>
        </el-form>
        <section class="top-btn-group">
            <section>
                <el-button type="primary" plain @click="handleAfterSelected(1)">自动选点</el-button>
                <el-button plain @click="handleAfterSelected(2)">移除未选点楼盘</el-button>
                <el-button plain @click="handleAfterSelected(3)">清空已选点位</el-button>
                <el-button plain @click="handleAfterSelected(4)">向下选择</el-button>
            </section>
            <section>
                <el-button plain @click="handleImport">批量导入楼盘</el-button>
                <el-button type="primary" @click="handlePoint">快速选中点位</el-button>
            </section>
        </section>
        <section class="table-contailer">
            <h5>已选楼盘列表</h5>
            <XcTable
                ref="buildingTableRef"
                border
                is-selectable
                :height="300"
                highlight-current-row
                :columns="selectedTableColumns"
                :data="selectedTableData"
                @selection-change="handleBuildingSeletionChange"
                @current-change="handleCurrentChange"
                @sort-change="handleSortChange"
            >
            </XcTable>
        </section>

        <section v-loading="pointLoading" class="handler-area">
            <section class="table-contailer">
                <h5>已选点位</h5>
                <XcTable
                    border
                    :height="250"
                    is-selectable
                    :columns="selectedPointTableColumns"
                    :data="selectedPointTableData"
                    @selection-change="handlePointSeletionChange"
                ></XcTable>
            </section>
            <section class="btn-group">
                <el-button
                    size="mini"
                    :disabled="!pointIds.length"
                    class="icon-button"
                    :loading="cancelLoading"
                    type="primary"
                    icon="arrow-right"
                    @click="toCancel"
                ></el-button>
                <el-button
                    class="icon-button"
                    size="mini"
                    :disabled="!unpointIds.length"
                    type="primary"
                    :loading="addLoading"
                    icon="arrow-left"
                    @click="toAdd"
                ></el-button>
            </section>
            <section class="table-contailer">
                <h5>未选点位</h5>
                <XcTable
                    border
                    is-selectable
                    :height="250"
                    :columns="selectedPointTableColumns"
                    :data="unselectedPointTableData"
                    :row-config="rowConfig"
                    @selection-change="handleUnpointSeletionChange"
                >
                    <template #handler="scope">
                        <el-button type="text">点位分析</el-button>
                    </template>
                </XcTable>
            </section>
        </section>
    </section>
    <AutoPointDialog
        v-if="showAddPoint"
        v-model="showAddPoint"
        :id-list="buildingIds"
        :point-property="pointProperty"
        @success="resetBuilding"
    />
    <HandelPointDialog
        v-model="showHandelPoint"
        :show-radio="false"
        title="快速选中点位"
        :plan-detail="currentPlan"
        @success="resetBuilding"
    />
    <HandelImportDialog
        v-model="showHandelImport"
        :point-property="pointProperty"
        title="批量导入楼盘"
        :plan-detail="currentPlan"
        @success="resetBuilding"
    />
    <PointAnalysis v-model="canAnalysisPoint" :point-ana="pointAnaly"></PointAnalysis>
</template>

<script lang="ts" setup>
import { defineProps, defineEmits, ref, reactive, onMounted, computed } from 'vue';
import XcTable from '@x-tech/fe-pc-components/src/components/XcTableTemplate/XcTable.vue';
import {
    analysisPoint,
    getSelected,
    getMachines,
    clearSelected,
    cancelSelected,
    addPoint,
    deleteBuilding,
} from '@/api/plan.ts';
import { propertyType, housePriceType } from '@/utils/config.ts';
import AutoPointDialog from './autoPointDialog.vue';
import HandelPointDialog from './handelPointDialog.vue';
import HandelImportDialog from './handelImportDialog.vue';
import PointAnalysis from './pointAnalysis.vue';
import { downLoadCommon } from '@/utils/common';
import { idItem, idsList } from '../programType.ts';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useStore } from 'vuex';
import { count } from 'console';

const store = useStore();
const planId = computed(() => store.state.plan.planId);
const emit = defineEmits<{(e: 'refresh'): void }>();
const props = defineProps({
    showDrawer: {
        type: Boolean,
        default: false,
    },
});
const pointValue = ref([1, 2]);
const currentBuildingParams = ref({});
const keywords = ref(null);
const cancelLoading = ref(false);
const addLoading = ref(false);
const showHandelPoint = ref(false);
const showHandelImport = ref(false);
const buildingIds = ref([]);
const buildingObject = ref([]);
const pointIds = ref([]);
const unpointIds = ref([]);
const currentPlan = ref({});
const buildingTableRef = ref(null);
const selectedTableData = ref([]);
const unselectedPointTableData = ref([]);
const selectedPointTableData = ref([]);
const showAddPoint = ref(false);
const targetBuildingId = ref(null);
const selectedTableColumns = [
    { label: '楼盘名称', key: 'name', prop: { sortable: 'custom' } },
    { label: '已选点位数', key: 'counts', prop: { sortable: 'custom' } },
    { label: '楼栋数', key: 'builds', prop: { sortable: 'custom' } },
    { label: '单元数', key: 'units', prop: { sortable: 'custom' } },
    { label: '可售点位数', key: 'machines', prop: { sortable: 'custom' } },
    { label: '区域', key: 'areaName', prop: { sortable: 'custom' } },
];
const selectedPointTableColumns = [
    { label: '点位编码', key: 'code', prop: { width: 170 } },
    { label: '楼栋', key: 'building', prop: { sortable: true, width: 130 } },
    { label: '单元', key: 'unit', prop: { sortable: true, width: 130 } },
    { label: '电梯', key: 'elevator', prop: { sortable: true, width: 150 } },
    { label: '设备型号', key: 'size', prop: { sortable: true, 'min-width': 150 } },
];
// V2.1.2_点位查询方案排斥需求加入
const canAnalysisPoint = ref(false);
let pointAnaly = reactive({});
const pointLoading = ref(false);
const handlenalysisPoint = async ({ row }) => {
    const params = {
        planId: planId.value,
        pointCodeList: [row.code],
    };
    pointLoading.value = true;
    let data = { canChoice: false };
    try {
        data = await analysisPoint(params);
    } catch (e) {
        console.log('e', e);
    } finally {
        pointLoading.value = false;
    }
    pointAnaly = Object.assign(pointAnaly, data);
    if (!data.canChoice) {
        // 点位是否可以调度(true,可以调度;false,无法调度)
        canAnalysisPoint.value = true;
    } else {
        ElMessageBox.confirm('可以调度', {
            confirmButtonText: '确定',
            showCancelButton: false,
            type: 'success',
            draggable: true,
            title: '提示',
        });
    }
};
const pointProperty = computed(() => (pointValue.value.length === 2 ? 0 : pointValue.value[0]));
const rowConfig = [{ on: handlenalysisPoint, type: 'button', color: '#4D88FF', name: '点位分析' }];

const getSelectedData = async () => {
    const params = {
        planId: planId.value,
        premisesName: keywords.value,
    };
    const data = await getSelected(params) || [];
    selectedTableData.value = data;
};
const getMachinesData = async (params = { planId: planId.value }) => {
    const data = await getMachines(params) || [];
    unselectedPointTableData.value = data.unselected;
    selectedPointTableData.value = data.selected;
};

const handleBuildingSeletionChange = (selected: idsList) => {
    buildingIds.value = selected.map(({ id }: idItem) => id);
    buildingObject.value = selected;
};
const handleSortChange = ({ prop, order }) => {
    if (!prop || !order) {
        return;
    }
    selectedTableData.value.sort((a, b) => {
        if (prop === 'name' || prop === 'areaName') {
            const result = a[prop].localeCompare(b[prop]);
            return order === 'ascending' ? result : -result;
        }
        if (order === 'ascending') {
            return a[prop] - b[prop];
        }
        return b[prop] - a[prop];
    });
};
const handlePointSeletionChange = (selected: idsList) => {
    pointIds.value = selected.map(({ code }: idItem) => code);
};
const handleUnpointSeletionChange = (selected: idsList) => {
    unpointIds.value = selected.map(({ code }: idItem) => code);
};

const handleClear = async () => {
    const params = {
        premisesIdList: buildingIds.value,
        planId: planId.value,
    };
    await clearSelected(params);
    ElMessage.success('操作成功');

    resetBuilding();
};
const handlePoint = () => {
    currentPlan.value = { planId: planId.value };
    showHandelPoint.value = true;
};
const handleImport = () => {
    currentPlan.value = { planId: planId.value };
    showHandelImport.value = true;
};
const handleSelectAfterBuilding = () => {
    const lastSelected = buildingIds.value[buildingIds.value.length - 1];

    const idx = selectedTableData.value.findIndex(({ id }) => id === lastSelected);
    const rows = selectedTableData.value.slice(idx + 1);
    const idsAfterSeleced = rows.map(({ id }) => id);

    buildingIds.value = [...buildingIds.value, ...idsAfterSeleced];
    rows.forEach((row) => {
        // TODO: improvement typing when refactor table
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-expect-error
        buildingTableRef.value!.xcTableRef.toggleRowSelection(row, undefined);
    });
};

const refreshBuilding = async () => {
    await getSelectedData();
    if (targetBuildingId.value) {
        await getSelectedData();
        const targetRow = selectedTableData.value.find((item) => item.id === targetBuildingId.value);
        if (targetRow) {
            buildingTableRef.value!.xcTableRef.setCurrentRow(targetRow);
        }
    }
};

const handleCurrentChange = (val, b) => {
    if (val) {
        const params = {
            premisesIdList: [val.id],
            planId: planId.value,
        };
        targetBuildingId.value = val.id;
        currentBuildingParams.value = params;
        getMachinesData(params);
    }
};

const toCancel = async () => {
    const params = {
        pointCodeList: pointIds.value,
        planId: planId.value,
    };
    if (!pointIds.value.length) {
        return ElMessage.warning('请选择点位');
    }
    cancelLoading.value = true;
    try {
        await cancelSelected(params);
        emit('refresh');
    } finally {
        cancelLoading.value = false;
    }

    getMachinesData(currentBuildingParams.value);
    refreshBuilding();
};
const toAdd = async () => {
    const params = {
        pointCodeList: unpointIds.value,
        planId: planId.value,
    };
    if (!unpointIds.value.length) {
        return ElMessage.warning('请选择点位');
    }
    addLoading.value = true;
    try {
        const { msg } = await addPoint(params);
        emit('refresh');
        if (msg) {
            await ElMessageBox.confirm(msg, '提示', {
                confirmButtonText: '确认',
                showCancelButton: false,
            });
        }
    } finally {
        addLoading.value = false;
    }

    // if (url) {
    //     downLoadCommon(url);
    // }
    getMachinesData(currentBuildingParams.value);
    refreshBuilding();
};
const handleRemove = async () => {
    const params = {
        premisesIdList: buildingObject.value.filter(({ counts }) => counts === 0).map(({ id }) => id),
        planId: planId.value,
    };

    if (!params.premisesIdList.length) {
        ElMessage.warning('请选中未选点的楼盘');
        return;
    }
    await deleteBuilding(params);
    resetBuilding();
    ElMessage.success('操作成功');
};

const handleAfterSelected = (type) => {
    if (!buildingIds.value.length) {
        return ElMessage.warning('请选择项目');
    }
    switch (type) {
        case 1:
            showAddPoint.value = true;
            break;
        case 2:
            handleRemove();
            break;
        case 3:
            handleClear();
            break;
        case 4:
            handleSelectAfterBuilding();
            break;
        default:
            break;
    }
};

const handleSearch = () => {
    const result = selectedTableData.value.find((item: { name: string }) => item.name.includes(keywords.value));
};

const resetBuilding = () => {
    getSelectedData();
    buildingIds.value = [];
    buildingObject.value = [];
    unselectedPointTableData.value = [];
    selectedPointTableData.value = [];
    pointIds.value = [];
    unpointIds.value = [];
    emit('refresh');
};
const initData = async () => {
    getSelectedData();
    getMachinesData();
};
getSelectedData();
</script>

<style lang="scss" scoped>
.container {
    background: #fff;
    padding: 0 20px 52px;
}

.table-contailer h5 {
    margin-top: 23px;
    margin-bottom: 10px;
}

.handler-area {
    width: 100%;
    display: flex;

    align-items: center;

    .table-contailer {
        h5 {
            margin-top: 30px;
        }

        width: calc((100% - 120px) / 2);
    }

    .btn-group {
        margin: 58px 20px 0;

        .el-button {
            display: block;
            width: 34px;
            height: 34px;
            min-width: auto;
            padding: 0;

            & + .el-button {
                margin: 20px 0 0;
            }
        }
    }
}

.top-btn-group {
    display: flex;
    justify-content: space-between;
}
</style>
